import { baseRequest } from './config'

// 基础请求类
export default class ReqClass {
    constructor(options) {
        this.defaultOptions = options || {} // 默认配置项
        this.apiList = {}   // 请求信息
    }
    // 基础请求方法
    api(options) {
        const apiName = options.url.replace(/\//g, '$_$')
        options = Object.assign({ apiName }, this.defaultOptions, options)
        options.url = options.baseUrl + options.url
        this.initState(apiName, options)
        if (options.debounce && this.getApiState(apiName) === 'pending') { return new Promise(() => { }) }
        this.setApiState(apiName, 'pending')
        return new Promise((resolve, reject) => {
            let requestConfig = this.requestBefore({
                ...options,
                success: (response) => {
                    if (options.debuglog) { console.log(response.data, `>>> ${options.url}`) }
                    let resRsult = this.responseBefore(response, options)
                    if (resRsult !== true) {
                        this.setApiState(apiName, 'fail');
                        return reject({ state: 'fail', response })
                    }
                    this.setApiState(apiName, 'success')
                    resolve(response.data);
                },
                fail: (err) => {
                    let errMsg = '服务器正在维护...'
                    console.log(errMsg)
                    this.toast(errMsg)
                    this.setApiState(apiName, 'error')
                    reject({ state: 'error', err });
                },
                complete: (res) => {
                    if (typeof options.complete === 'function') {
                        options.complete.call(this, res)
                    }
                }
            })
            if (!requestConfig) { return new Promise(() => { }) }
            // 开始请求
            baseRequest(requestConfig)
        })
    }
    // 初始化请求状态
    initState(apiName, options) {
        if (!apiName) return
        if (typeof this.apiList[apiName] === 'undefined') {
            this.apiList[apiName] = { state: 'init', options, startTime: Date.now(), count: 1 }
        } else {
            this.apiList[apiName].startTime = Date.now()
            this.apiList[apiName].count++
        }
    }
    // 获取请求状态
    getApiState(apiName) {
        return this.apiList[apiName].state
    }
    // 设置请求状态
    setApiState(apiName, state) {
        this.apiList[apiName].state = state
    }
    // 请求拦截器... 需返回config对象，若不反回config则不会发起请求
    requestBefore(config) {
        // 相关拦截操作请重写
        return config
    }
    // 响应拦截器...成功返回true，失败返回false
    responseBefore(res, options) {
        // 相关拦截操作请重写
        return true
    }
    // 请求提示信息
    toast(msg) {
        console.log(msg, '-->>> toast msg')
    }
}